package com.salon.modules.oss.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.salon.common.exception.CustomException;
import com.salon.common.http.response.PageResult;
import com.salon.modules.oss.entity.QiniuConfig;
import com.salon.modules.oss.entity.QiniuFile;
import com.salon.modules.oss.mapper.QiniuFileMapper;
import com.salon.modules.oss.service.QiniuFileService;
import com.salon.modules.oss.utils.FileUtil;
import com.salon.modules.oss.utils.QiNiuUtil;
import com.salon.modules.oss.vo.QiniuFileQueryCriteria;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "qiNiu")
public class QiniuFileServiceImpl extends ServiceImpl<QiniuFileMapper, QiniuFile> implements QiniuFileService {

    private final QiniuFileMapper qiniuFileMapper;

    @Value("${qiniu.max-size}")
    private Long maxSize;

    @Override
    public PageResult<QiniuFile> queryAll(QiniuFileQueryCriteria criteria, Page<Object> page){
        IPage<QiniuFile> list = qiniuFileMapper.findAll(criteria, page);
        return new PageResult<>(list.getTotal(), list.getCurrent(), list.getSize(), list.getRecords());
    }

    @Override
    public List<QiniuFile> queryAll(QiniuFileQueryCriteria criteria) {
        return qiniuFileMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QiniuFile upload(MultipartFile file, QiniuConfig qiniuConfig) {
        FileUtil.checkSize(maxSize, file.getSize());
        if(qiniuConfig.getId() == null){
            throw new CustomException("请先添加相应配置，再操作");
        }
        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(qiniuConfig.getZone()));
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        String upToken = auth.uploadToken(qiniuConfig.getBucket());
        try {
            String key = file.getOriginalFilename();
            if(qiniuFileMapper.findByKey(key) != null) {
                key = QiNiuUtil.getKey(key);
            }
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            QiniuFile content = qiniuFileMapper.findByKey(FileUtil.getFileNameNoEx(putRet.key));
            if(content == null){
                //存入数据库
                QiniuFile qiniuFile = new QiniuFile();
                qiniuFile.setSuffix(FileUtil.getExtensionName(putRet.key));
                qiniuFile.setBucket(qiniuConfig.getBucket());
                qiniuFile.setType(qiniuConfig.getType());
                qiniuFile.setKey(FileUtil.getFileNameNoEx(putRet.key));
                qiniuFile.setUrl(qiniuConfig.getHost() + "/" + putRet.key);
                qiniuFile.setSize(FileUtil.getSize(Integer.parseInt(String.valueOf(file.getSize()))));
                save(qiniuFile);
            }
            return content;
        } catch (Exception e) {
           throw new CustomException(e.getMessage());
        }
    }

    @Override
    public String download(QiniuFile content, QiniuConfig config){
        String finalUrl;
        String type = "公开";
        if(type.equals(content.getType())){
            finalUrl  = content.getUrl();
        } else {
            Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
            // 1小时，可以自定义链接过期时间
            long expireInSeconds = 3600;
            finalUrl = auth.privateDownloadUrl(content.getUrl(), expireInSeconds);
        }
        return finalUrl;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(QiniuFile content, QiniuConfig config) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(content.getBucket(), content.getKey() + "." + content.getSuffix());
        } catch (QiniuException ex) {
            ex.printStackTrace();
        } finally {
            removeById(content);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synchronize(QiniuConfig config) {
        if(config.getId() == null){
            throw new CustomException("请先添加相应配置，再操作");
        }
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(config.getBucket(), prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            QiniuFile qiniuFile;
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                if(qiniuFileMapper.findByKey(FileUtil.getFileNameNoEx(item.key)) == null){
                    qiniuFile = new QiniuFile();
                    qiniuFile.setSize(FileUtil.getSize(Integer.parseInt(String.valueOf(item.fsize))));
                    qiniuFile.setSuffix(FileUtil.getExtensionName(item.key));
                    qiniuFile.setKey(FileUtil.getFileNameNoEx(item.key));
                    qiniuFile.setType(config.getType());
                    qiniuFile.setBucket(config.getBucket());
                    qiniuFile.setUrl(config.getHost()+"/"+item.key);
                    save(qiniuFile);
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Long[] ids, QiniuConfig config) {
        for (Long id : ids) {
            delete(getById(id), config);
        }
    }

    @Override
    public void downloadList(List<QiniuFile> queryAll, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (QiniuFile content : queryAll) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("文件名", content.getKey());
            map.put("文件类型", content.getSuffix());
            map.put("空间名称", content.getBucket());
            map.put("文件大小", content.getSize());
            map.put("空间类型", content.getType());
            map.put("创建日期", content.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
